#include <stdio.h>
#include <string.h>
#include "hash.h"

// 哈希函数：将字符串 key 映射为哈希表索引
unsigned int hsh_function(const void *key, int capacity) 
{
    unsigned int seed = 131;  // 哈希种子（经验值，减少冲突）
    unsigned int hash = 0;

    char *buff = (char*)key;
    
    // 遍历字符串，计算哈希值
    while (*buff) {
        hash = hash * seed + (*buff++);
    }
    
    // 确保索引在 [0, capacity-1] 范围内
    return hash % capacity;
}

int compareChar(void* a, void* b)
{
    const char* str_a = (const char*)a;
    const char* str_b = (const char*)b;
    return strcmp(str_a, str_b); 
}


int main()
{
    g_compare = compareChar;
    g_hash_func = hsh_function;

    HashTable *hashTable = hash_table_init(16);
    hash_insert(hashTable,"user",sizeof("user"),"zhw",sizeof("zhw"));
    hash_insert(hashTable,"pwd",sizeof("pwd"),"1234",sizeof("1234"));
    hash_insert(hashTable,"uuu",sizeof("uuu"),"1",sizeof("1"));
    HashNode* node = hash_get(hashTable,"user");
    HashNode* node1 = hash_get(hashTable,"pwd");
    HashNode* node2 = hash_get(hashTable,"uuu");
    printf("%s\n",(char*)node->value);
    printf("%s\n",(char*)node1->value);
    printf("%s\n",(char*)node2->value);

    hash_modify(hashTable,"user",sizeof("user"),"chx",sizeof("chx"));
    printf("%s\n",(char*)node->value);
    printf("%s\n",(char*)node1->value);
    printf("%s\n",(char*)node2->value);

    printf("hash_delete before size=%d\n",hashTable->size);
    int res = hash_delete(hashTable,"user");
    if (res == -1)
    {
        printf("hash_delete error\n");
    }
    else if (res == 0)
    {
        printf("success\n");
    }
    else
    {
        printf("no exist\n");
    }

    
    node = hash_get(hashTable,"user");
    node1 = hash_get(hashTable,"pwd");
    node2 = hash_get(hashTable,"uuu");
    if (node == NULL)
    {
        printf("node no exist\n");
    }
    else
    {
        printf("%s\n",(char*)node->value);
    }
    printf("%s\n",(char*)node1->value);
    printf("%s\n",(char*)node2->value);

    printf("clear before size=%d\n",hashTable->size);
    hash_table_clear(hashTable);
    printf("clear after size=%d\n",hashTable->size);
    
    return 0;
}